#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Copyright (C) 2025 Huawei Technologies Co., Ltd. All rights reserved.

import os
import subprocess
import sys
import logging

from openubmc_ansible.utils import BMC_EXCU_PATH

logging.basicConfig(format="%(message)s")


def delete_log():
    """
    Function:
        Deletes files generated during plug-in running.
    Args:
        None
    Returns:
        delete: bool, whether the file is deleted successfully.
    Raises:
        None
    Date: 6/24/2021
    """
    flag_remove_example = False
    delete = True
    ansible_folders = []
    for cur_dir, folders, _ in os.walk("/home"):
        for folder in folders:
            if folder != "ansible_bmc":
                continue
            parent_dir_name = os.path.basename(cur_dir)
            if parent_dir_name != "openUBMC_ansible_Module":
                ansible_folders.append(os.path.join(cur_dir, folder))

    if not ansible_folders:
        logging.error("can not find openubmc_ansible log.")
        return False

    while True:
        logging.error("do you want to keep the log files and plug-in generation file?(y/n)")
        choice = ansible_input()
        if choice in ['y', 'Y']:
            break
        elif choice in ['n', 'N']:
            flag_remove_example = True
            break
        else:
            logging.warning("you have press the wrong key")
    if not flag_remove_example:
        return True

    for folder in ansible_folders:
        ret = subprocess.call(["/usr/bin/rm", "-rf", folder], shell=False)
        if ret != 0:
            logging.error("rm %s failed!" % folder)
            delete = False
    if delete:
        logging.error("rm openubmc_ansible log successfully!")
    return delete


def delete_install_file():
    """
    Function:
        Deletes files generated during plug-in installation.
    Args:
        None
    Returns:
        delete: bool, whether the file is deleted successfully.
    Raises:
        None
    Date: 6/24/2021
    """
    ansible_installed_path = ansible.__path__[0]
    openubmc_lib_path = os.path.join(ansible_installed_path, "modules")
    flag_remove_example = False
    delete = True

    if not os.path.exists(os.path.join(openubmc_lib_path, 'openubmc')):
        logging.error("can not find openubmc_ansible module!")
        return False
    while True:
        logging.error("do you want to keep the yml files? (y/n)")
        choice = ansible_input()
        if choice in ['y', 'Y']:
            break
        elif choice in ['n', 'N']:
            flag_remove_example = True
            break
        else:
            logging.warning("you have press the wrong key")
    ret = subprocess.call(
        ["/usr/bin/rm", "-rf", os.path.join(openubmc_lib_path, 'openubmc')], shell=False)
    if ret != 0:
        logging.error("rm openubmc_ansible_module failed!")

    openubmc_utils_path = os.path.join(ansible_installed_path, "../")
    openubmc_utils_path = os.path.join(openubmc_utils_path, "openubmc_ansible")

    ret = subprocess.call(["/usr/bin/rm", "-rf", openubmc_utils_path], shell=False)
    if ret != 0:
        delete = False
        logging.error("rm openubmc_ansible_refish api failed!")
    if flag_remove_example:
        ret = subprocess.call(["/usr/bin/rm", "-rf", BMC_EXCU_PATH], shell=False)
        if ret != 0:
            delete = False
            logging.error("rm openubmc ansible yml failed!")
    return delete


if __name__ == "__main__":
    try:
        import ansible
        from ansible.module_utils.six.moves import input as ansible_input
    except ImportError as e:
        logging.error("Ansible is not installed.")
        sys.exit(1)

    logging.error('start uninstalling openUBMC ansible module')

    delete_install = delete_install_file()
    delete_log = delete_log()
    if delete_install and delete_log:
        logging.error("uninstalling openUBMC ansible successfully!")
        sys.exit(1)
    else:
        sys.exit(0)
